package cn.tjad.tjad2.net.http;

import android.text.TextUtils;

import java.io.IOException;

import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.consts.UrlConsts;
import cn.tjad.tjad2.net.NetworkUtils;
import okhttp3.Interceptor;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.Util;

public class RequestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        if (!NetworkUtils.isAvailable(TjadApplication.getInstance())) {
            return new Response.Builder()
                    .request(chain.request())
                    .protocol(Protocol.HTTP_1_1)
                    .code(426)
                    .message("当前网络不可用")
                    .body(Util.EMPTY_RESPONSE)
                    .sentRequestAtMillis(-1L)
                    .receivedResponseAtMillis(System.currentTimeMillis())
                    .build();
        }
        final Request.Builder builder = chain.request().newBuilder();
        String url = chain.request().url().toString();
        if (url.equals(UrlConsts.USER_AUTH)) {
            return chain.proceed(builder.build());
        } else if (TjadApplication.getInstance().getSession() == null || TextUtils.isEmpty(TjadApplication.getInstance().getSession().getToken())) {
            //没有保存token，需要跳转到登录页面
            return new Response.Builder()
                    .request(chain.request())
                    .protocol(Protocol.HTTP_1_1)
                    .code(401)
                    .message("登录态失效，请重新登录")
                    .body(Util.EMPTY_RESPONSE)
                    .sentRequestAtMillis(-1L)
                    .receivedResponseAtMillis(System.currentTimeMillis())
                    .build();
        }
        builder.header("Authorization", "bearer " + TjadApplication.getInstance().getSession().getToken());
        return chain.proceed(builder.build());
    }
}
